package com.spice.im;


import java.util.ArrayList;














import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import me.maxwin.view.XListViewHeader;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;


//import com.example.android.bitmapfun.util.AsyncTask;
import com.beem.push.utils.AsyncTask;
import com.dodowaterfall.widget.FlowView;
import com.example.android.bitmapfun.util.ObjectCache;
//import com.stb.core.pojo.UploadFileRequest;
import com.speed.im.login.ContactGroup;
import com.speed.im.login.ContactGroupListIQ;
import com.speed.im.login.ContactGroupListIQResponse;
import com.speed.im.login.ContactGroupListIQResponseProvider;
import com.speed.im.login.EncryptionUtil;
import com.spice.im.chat.ChatActivity;
import com.spice.im.ui.BadgeView;
import com.spice.im.ui.CustomListView;
import com.spice.im.ui.HandyTextView;
import com.spice.im.ui.CustomListView.OnLoadMoreListener;
import com.spice.im.ui.CustomListView.OnRefreshListener;
import com.spice.im.utils.ConstantValues;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.ImageFetcher;
import com.spice.im.utils.TextUtils;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onMiddleImageButtonClickListener;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.spice.im.utils.SwitcherButton.onSwitcherButtonClickListener;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.IConnectionStatusCallback;
//import com.stb.isharemessage.service.Contact;
import com.stb.isharemessage.service.XmppConnectionAdapter;
import com.stb.isharemessage.service.aidl.IXmppFacade;
import com.stb.isharemessage.utils.BeemConnectivity;
//import com.test.HandyTextView;
//import com.test.MainActivity;
//import com.test.R;

//import dalvik.system.VMRuntime;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentTransaction;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.RecyclerListener;
import android.widget.AdapterView.OnItemClickListener;

import com.spice.im.utils.SwitcherButton.SwitcherButtonState;

public class MainActivity extends Activity implements IConnectionStatusCallback,OnClickListener{
	private View mNetErrorView;
	private TextView mConnect_status_info;
	private ImageView mConnect_status_btn;
	private Context mContext;
    private exPhoneCallListener myPhoneCallListener = null;
    private TelephonyManager tm = null;
	
    private final static float TARGET_HEAP_UTILIZATION = 0.75f;
    private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
    private static final Intent SERVICE_INTENT = new Intent();
	static {
		//pkg,cls
//		SERVICE_INTENT.setComponent(new ComponentName("com.test", "com.stb.isharemessage.BeemService"));
//		SERVICE_INTENT.setComponent(new ComponentName("com.stb.isharemessage", "com.stb.isharemessage.BeemService"));
		SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));//自身应用pkg名称，非service所在pkg名称
	}
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
    	LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
    protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}
	private final ServiceConnection mServConn = new BeemServiceConnection();
    private boolean mBinded = false;
    private IXmppFacade mXmppFacade;
    protected FlippingLoadingDialog mLoadingDialog;
    private HeaderLayout mHeaderLayout;
    private XListViewHeader xListViewHeader;
    private ImageFetcher mImageFetcher;
	private int itemWidth;
	private int column_count = 3;// 显示列数 just for image cut
//	protected void showLoadingDialog(String text) {
//		if (text != null) {
//			mLoadingDialog.setText(text);
//		}
//		mLoadingDialog.show();
//	}
//
//	protected void dismissLoadingDialog() {
//		if (mLoadingDialog.isShowing()) {
//			mLoadingDialog.dismiss();
//		}
//	}
    
	protected void showLoadingDialog() {
		findViewById(R.id.pb).setVisibility(View.VISIBLE);	
	}

	protected void dismissLoadingDialog() {
		findViewById(R.id.pb).setVisibility(View.GONE);
	}
	
//	private Button btn;
	private final OkListener mOkListener = new OkListener();
//	private TextView udidTextView;
    //----------------------版块滑动部分数据---------------------------//
    private int screenWidth;//屏幕的宽度
	private int imgWidth;   // 图片宽度
	private int currentView=0;// 当前视图
	private int viewOffset;// 动画图片偏移量
	
	//----------------------刷新部分数据----------------------------//
	private static final int LOAD_DATA_FINISH = 10;
	private static final int REFRESH_DATA_FINISH = 11;
	private CustomListAdapter mAdapter;
	private CustomListView mListView;
	
	private final ContactGroupListOnClick mOnContactClick = new ContactGroupListOnClick();/**单击某联系人，打开chat聊天对话框*/
	
//	private LinkedList<ContactGroup> tempList;
	private Map<View,CustomListAdapter> maps=new HashMap<View, CustomListAdapter>();
	private Map<View,CustomListView> mapList=new HashMap<View, CustomListView>();
	
    public void onCreate(Bundle savedInstanceState) {
//    	VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);
//    	VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //设置最小heap内存为6MB大小。当然对于内存吃紧来说还可以通过手动干涉GC去处理
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.activity_main);
    	mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
    	
		mHeaderLayout = (HeaderLayout) findViewById(R.id.login_header);
//		mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
//		mHeaderLayout.setTitleRightImageButton("联系人列表", null,
//				R.drawable.refresh2,
//				new OnRightImageButtonClickListener());
		
		mHeaderLayout.init(HeaderStyle.TITLE_CONTACTLIST);
		mHeaderLayout.setTitleContactList(R.drawable.ic_chat_dis_1,
				R.drawable.bg_chat_dis_active, 
				"好友列表", "招呼盒子",
				R.drawable.refresh2,new OnMiddleImageButtonClickListener(),
				"好友", "招呼", new OnSwitcherButtonClickListener());
		
        xListViewHeader = (XListViewHeader)findViewById(R.id.xlistview_header);
        xListViewHeader.setVisiableHeight(60);
        xListViewHeader.setState(0);
        xListViewHeader.setVisibility(View.VISIBLE);
        
        
        mImageFetcher = new ImageFetcher(this, 240);
        mImageFetcher.setUListype(0);////0普通图片listview 1瀑布流  2地图模式
        mImageFetcher.setLoadingImage(R.drawable.empty_photo);
        
        itemWidth = this.getWindowManager().getDefaultDisplay().getWidth() / column_count;// 根据屏幕大小计算每列宽度
        
        
        initRefreshView(linkedList);
		
//    	btn = (Button)findViewById(R.id.button1);
//        btn.setOnClickListener(mOkListener);
//        udidTextView = (TextView)findViewById(R.id.udid_name);
        mContext = this;
        mNetErrorView = findViewById(R.id.net_status_bar_top);
        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
        mConnect_status_btn.setOnClickListener(this);
        
	    IntentFilter mFilter = new IntentFilter();
	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
	    registerReceiver(mNetWorkReceiver, mFilter);
	    
        /* 添加自己实现的PhoneStateListener */
        myPhoneCallListener = new exPhoneCallListener();
       
       /* 取得电话服务 */
        tm =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
       
        /* 注册电话通信Listener */
        tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_CALL_STATE);
        
    	BeemApplication.getInstance().addActivity(this);
    	
//    	ObjectCache.saveStatus("isConnected", true, this);//标识为手动启动
    }
	@Override
	public void onClick(View v) {
		//网络设置
		if(v.getId() == R.id.net_status_bar_btn){
			setNetworkMethod(this);
		}
	}
    @Override
    protected void onResume() {
		super.onResume();
		if (!mBinded){
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);	    
		}
		mImageFetcher.setExitTasksEarly(false);
    }
    public void onPause() {
    	super.onPause();
    	mImageFetcher.setExitTasksEarly(true);
    	Log.e("================2015 TestActivity.java ================", "++++++++++++++onPause()++++++++++++++mBinded="+mBinded);
//		if (mBinded) {
//			unbindService(mServConn);
//			mBinded = false;
//		}
    }
    /**
     * 重写finish()方法
     */
    @Override
    public void finish() {
        //super.finish(); //记住不要执行此句
        moveTaskToBack(true); //设置该activity永不过期，即不执行onDestroy()
    }   
 
    public void finishNew() {
        super.finish(); //记住要执行此句
        moveTaskToBack(false);
    }
    @Override
    protected void onDestroy() {
		super.onDestroy();
		Log.e("================2015 TestActivity.java ================", "++++++++++++++onDestroy()000++++++++++++++mBinded="+mBinded);
		mImageFetcher.onCancel();
		clearAsyncTask();
    	Log.e("================2015 TestActivity.java ================", "++++++++++++++onDestroy()111++++++++++++++");
// 	    XmppConnectionAdapter.isPause = true;
//		if(XmppConnectionAdapter.instance!=null)
//			XmppConnectionAdapter.instance.resetApplication();
//		XmppConnectionAdapter.instance = null;
//		stopService(SERVICE_INTENT);
		Log.e("================2015 TestActivity.java ================", "++++++++++++++onDestroy()222++++++++++++++");
//		loadingView.isStop = true;
	    try{
		    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
		    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
	    }catch (RemoteException e) {
	    	e.printStackTrace();
	    }
		if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}

		mXmppFacade = null;
		
		unregisterReceiver(mNetWorkReceiver); // 删除广播
		if(tm!=null){
			tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_NONE);//取消监听即可
			tm = null;
		}
		if(myPhoneCallListener!=null)
			myPhoneCallListener = null;
		
		BeemApplication.getInstance().exit();
		Log.e("================2015 TestActivity.java ================", "++++++++++++++onDestroy()333++++++++++++++");
    }
    /**
     * The service connection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {
		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	mBinded = true;
		    	try{
		    		mXmppFacade.getXmppConnectionAdapter().registerConnectionStatusCallback(MainActivity.this);
		    		
		    	}catch(Exception e){
		    		e.printStackTrace();
		    	}
//		    	getContactList();
//		    	getData(0);
		    	getContactList(0);
		    }
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
		    try{
			    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
			    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
		    }catch (RemoteException e) {
		    	e.printStackTrace();
		    }
		    mXmppFacade = null;
		    mBinded = false;
		}
    }
//    private List<Contact> mListContact;
    private LinkedList linkedList = new LinkedList();
	private String searchkey = "";
	private String searchtype = "0";
	private String ages = "12";
	private String genders = "1";
	private String distances = "5000";
	private String online = "0";
	private String[] errorMsg = new String[]{"抱歉,没有找到相关结果.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"",
			"请求异常,稍候重试!"};
	private int errorType = 5;
    private int currentPage = 0;
    private int numberresult = 50;
	public boolean initContactList(){
		Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()111++++++++++++++");
		if(BeemConnectivity.isConnected( getApplicationContext())){
			Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()222++++++++++++++");
		    try {
		    	if(mXmppFacade!=null){
		    		Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()333++++++++++++++");
			    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
			    			){
			    		
			    		ContactGroupListIQ reqXML = new ContactGroupListIQ();
			            reqXML.setId("1234567890");
			            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
			            reqXML.setUid("2");//2
			            reqXML.setPage("0");
			            reqXML.setGroupstr("1");
			            reqXML.setSearchkey(searchkey);//searchkey
			            reqXML.setView("me");
			            reqXML.setFieldid("0");
			            reqXML.setOrderby("threadnum");
			            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
					    String login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
			            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,login);
			            reqXML.setUuid(uuid);
//			            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
			            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ "me"+"threadnum"+uuid;
			            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
			            reqXML.setHashcode(hash_dest);
			            reqXML.setType(IQ.Type.SET);
			            String elementName = "contactgrouplistiq"; 
			    		String namespace = "com:isharemessage:contactgrouplistiq";
			    		ContactGroupListIQResponseProvider provider = new ContactGroupListIQResponseProvider();
			            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "contactgrouplistiq", "com:isharemessage:contactgrouplistiq", provider);
			            
			            if(rt!=null){
			                if (rt instanceof ContactGroupListIQResponse) {
			                	final ContactGroupListIQResponse contactGroupListIQResponse = (ContactGroupListIQResponse) rt;

			                    if (contactGroupListIQResponse.getChildElementXML().contains(
			                            "com:isharemessage:contactgrouplistiq")) {
//			    					MainActivity.this.runOnUiThread(new Runnable() {
//				                    	
//            							@Override
//            							public void run() {
//            								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
//            							}
//            						});
			                        String Id = contactGroupListIQResponse.getId();
			                        String Apikey = contactGroupListIQResponse.getApikey();
			                        ArrayList cGroups = contactGroupListIQResponse.getCGroups();
			                        if(cGroups.size()!=0){
				                        linkedList = new LinkedList(cGroups);
//			                        	for(int q=0;q<cGroups.size();q++){
//			                        		linkedList.add(cGroups.get(q));
//			                        	}
				                        Log.e("响应packet结果解析...............", "Id="+Id+";Apikey="+Apikey); 
	//			                        mListContact = new ArrayList<Contact>(); 
	//			                        for(int k=0;k<cGroups.size();k++){
	//			                        	Log.e("响应packet结果解析...............", "cGroups"); 
	////			                        	mListContact.add(contact);
	//			                        }
				                        cGroups = null;
				                        return true;
			                        }
			                    }
			                } 
			            }
			            
			    		Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()444++++++++++++++");

			    	    if(linkedList!=null && linkedList.size()!=0)
			    	    	errorType = 5;
			    	    else{
			    	    	if(linkedList!=null && linkedList.size()==0)
			    	    		errorType = 0;
			    	    	else
			    	    		errorType = 6;
			    	    }
						mBinded = true;//20130804 added by allen
			    	}else
			    		errorType = 1;
		    	}else
		    		errorType = 2;
				
		    } catch (RemoteException e) {
		    	errorType = 3;
		    	e.printStackTrace();
		    	
		    } catch (Exception e){
		    	errorType = 3;
		    	e.printStackTrace();
		    }
	    }else{
	    	errorType = 4;
	    }
		return false;
	}
	private boolean flag = false;
//	private boolean isWork = false;
	private void getContactList(final int type) {
//		private View view2;
//		private int type2;
		if(!isWork){
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
//				showLoadingDialog("正在加载,请稍后...");
//				showLoadingDialog();
//				if(type==0){
//					showLoadingDialog();
//				}
				if(flag || (type==0)){
//					showLoadingDialog("正在加载,请稍后...");
					xListViewHeader.setShowText("正在加载,请稍候...");
					xListViewHeader.setVisibility(View.VISIBLE);
					xListViewHeader.setState(2);
				}
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				return initContactList();
//				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
//				dismissLoadingDialog();
//				if(type==0){
////					   view.findViewById(R.id.pb).setVisibility(View.GONE);
//					dismissLoadingDialog();
//				}
//				if(flag || (type==0)){
//					xListViewHeader.setState(0);
//					xListViewHeader.setVisibility(View.GONE);
//				}
//				if (!result) {
//					showCustomToast("数据加载失败...");
//					mHandler2.sendEmptyMessage(3);
//				} else {
//					mHandler2.sendEmptyMessage(0);
//				}
				if (result) {	
//					parserJsonData(result,type,view);
//					initRefreshView(linkedList);
					parserData(type);
//					getData(2);
//					Message load = mHandler.obtainMessage(LOAD_DATA_FINISH, linkedList);
//					mHandler.sendMessage(load);
					
//					Message refresh = mHandler.obtainMessage(REFRESH_DATA_FINISH,
//							tempList);
//					mHandler.sendMessage(refresh);
				}else{
					//提示没有获取到数据：可能网络问题
					mHandler.sendEmptyMessage(0);
				}
//				if(type==0){
//				   view.findViewById(R.id.pb).setVisibility(View.GONE);
//				}
				if(flag || (type==0)){
					xListViewHeader.setState(0);
					xListViewHeader.setVisibility(View.GONE);
				}
				flag = false;
				isWork = false;
			}

		});
		isWork = true;
		}
	}
	
	
	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(MainActivity.this).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(MainActivity.this);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
//	Handler mHandler2 = new Handler() {
//
//		@Override
//		public void handleMessage(android.os.Message msg) {
//			super.handleMessage(msg);
//			switch (msg.what) {
//			case 0:
//				if(errorType==5 && linkedList!=null){
//					Contact contact = null;
//			        for (int i = 0; i < linkedList.size(); i++) {
//			        	contact = (Contact)mListContact.get(i);
//			        	Log.e("MMMMMMMMMMMM20140714(2)MMMMMMMMMMMM", "++++++++++++++"+contact.toString()+"++++++++++++");
//			        }
//				}else{
//		        	showCustomToast(errorMsg[errorType]);
//		        }
//				break;
//
//			case 1:
//				
//				showCustomToast("已达顶端!");
//				break;
//			case 2:
//				
//				showCustomToast("已达底端!");
//				break;
//			default:
//				
//				break;
//			}
//		}
//
//	};
    private class OkListener implements OnClickListener {
    	
		/**
		 * Constructor.
		 */
		public OkListener() { }
	
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.button1:
//				getContactList();
//				getData(0);
				getContactList(0);
				break;
			default:
				break;
			}
		}
    };
    
	@Override
	public void connectionStatusChanged(int connectedState, String reason) {
		Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
		switch (connectedState) {
		case 0://connectionClosed
			mHandler3.sendEmptyMessage(0);
			break;
		case 1://connectionClosedOnError
//			mConnectErrorView.setVisibility(View.VISIBLE);
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("连接异常!");
			mHandler3.sendEmptyMessage(1);
			break;
		case 2://reconnectingIn
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("连接中...");
			mHandler3.sendEmptyMessage(2);
			break;
		case 3://reconnectionFailed
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("重连失败!");
			mHandler3.sendEmptyMessage(3);
			break;
		case 4://reconnectionSuccessful
//			mNetErrorView.setVisibility(View.GONE);
			mHandler3.sendEmptyMessage(4);

		default:
			break;
		}
	}
	Handler mHandler3 = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				break;

			case 1:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("连接异常!");
				break;

			case 2:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("连接中...");
				break;
			case 3:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("重连失败!");
				break;
				
			case 4:
				mNetErrorView.setVisibility(View.GONE);
				String udid = "";
				String partnerid = "";
				try{
					udid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().UDID;
					partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
				}catch(Exception e){
					e.printStackTrace();
				}
//				udidTextView.setText("udid="+udid);
//				partneridEditText.setText(partnerid);
//				getContactList();//20141025 added by allen
				break;
			case 5:
				mNetErrorView.setVisibility(View.VISIBLE);
				mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
				break;
			case 6:
				if(mXmppFacade!=null 
//						&& mXmppFacade.getXmppConnectionAdapter()!=null 
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
						&& BeemConnectivity.isConnected(mContext)){
					
				}else{
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("网络可用,连接中...");
				}
				break;	
			}
		}

	};
	private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();  
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
                Log.d("PoupWindowContactList", "网络状态已经改变");  
//                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
//                info = connectivityManager.getActiveNetworkInfo();    
//                if(info != null && info.isAvailable()) {  
//                    String name = info.getTypeName();  
//                    Log.d(tag, "当前网络名称：" + name);  
//                    //doSomething()  
//                } else {  
//                    Log.d(tag, "没有可用网络");  
//                  //doSomething()  
//                }  
                if(BeemConnectivity.isConnected(context)){
//                	mNetErrorView.setVisibility(View.GONE);
//                	isconnect = 0;
                	mHandler3.sendEmptyMessage(6);//4
                }else{
//                	mNetErrorView.setVisibility(View.VISIBLE);
//                	isconnect = 1;
                	mHandler3.sendEmptyMessage(5);
                	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
                }
            } 
        }
	};
	
	private boolean phonestate = false;//false其他， true接起电话或电话进行时 
    /* 内部class继承PhoneStateListener */
    public class exPhoneCallListener extends PhoneStateListener
    {
        /* 重写onCallStateChanged
        当状态改变时改变myTextView1的文字及颜色 */
        public void onCallStateChanged(int state, String incomingNumber)
        {
          switch (state)
          {
            /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
            case TelephonyManager.CALL_STATE_IDLE:
            	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
            	if(phonestate){
            		onPhoneStateResume();
            	}
            	phonestate = false;
              break;
            /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
            case TelephonyManager.CALL_STATE_OFFHOOK:
            	Log.e("================20131216 接起电话时================", "接起电话时");
            	onPhoneStatePause();
            	phonestate = true;
              break;
            /* 电话进来时 :在通话的过程中*/
            case TelephonyManager.CALL_STATE_RINGING:
//              getContactPeople(incomingNumber);
            	Log.e("================20131216 电话进来时================", "电话进来时");
//            	onBackPressed();
            	onPhoneStatePause();
            	phonestate = true;
              break;
            default:
              break;
          }
          super.onCallStateChanged(state, incomingNumber);
        }
    }
    
    protected void onPhoneStatePause() {
//		super.onPause();
    	try{

		if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}
		mXmppFacade = null;
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    protected void onPhoneStateResume() {
//		super.onResume();
    	try{
		if (!mBinded){
//		    new Thread()
//		    {
//		        @Override
//		        public void run()
//		        {
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);

//		        }
//		    }.start();		    
		}
		if (mBinded){
			mImageFetcher.setExitTasksEarly(false);
		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    /*
     * 打开设置网络界面
     * */
    public static void setNetworkMethod(final Context context){
        //提示对话框
        AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Intent intent=null;
                //判断手机系统的版本  即API大于10 就是3.0或以上版本 
                if(android.os.Build.VERSION.SDK_INT>10){
                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                }else{
                    intent = new Intent();
                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
                    intent.setComponent(component);
                    intent.setAction("android.intent.action.VIEW");
                }
                context.startActivity(intent);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        }).show();
    }
    
    
	/**
	 * ListView数据适配器
	 * @author Administrator
	 *  
	 */
	private class CustomListAdapter extends BaseAdapter implements RecyclerListener{

		private LayoutInflater mInflater;
		public LinkedList<ContactGroup> mList;

		public CustomListAdapter(Context pContext, LinkedList<ContactGroup> pList) {
			mInflater = LayoutInflater.from(pContext);
			if(pList != null){
				mList = pList;
			}else{
				mList = new LinkedList<ContactGroup>();
			}
		}
		
		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (getCount() == 0) {
				return null;
			}
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.listitem_contacts, null);

				holder = new ViewHolder();
				holder.imageView = (FlowView)convertView.findViewById(R.id.news_pic);
//				holder.mTitle = (TextView) convertView.findViewById(R.id.news_title);
//				holder.mContent = (TextView) convertView.findViewById(R.id.news_content);
//				holder.mGentie=(TextView) convertView.findViewById(R.id.news_gentiecount);
				holder.contentView = (HandyTextView) convertView.findViewById(R.id.user_item_htv_name);//昵称
                holder.user_item_layout_gender = (LinearLayout)convertView.findViewById(R.id.user_item_layout_gender);
                holder.user_item_iv_gender = (ImageView)convertView.findViewById(R.id.user_item_iv_gender);
                holder.user_item_htv_age = (HandyTextView)convertView.findViewById(R.id.user_item_htv_age);
                
                holder.user_item_htv_account = (HandyTextView)convertView.findViewById(R.id.user_item_htv_account);//帐号
                holder.user_item_htv_sign = (HandyTextView)convertView.findViewById(R.id.user_item_htv_sign);//个性签名
                holder.user_item_iv_icon_group_role = (ImageView)convertView.findViewById(R.id.user_item_iv_icon_group_role);
                holder.user_item_relative = (RelativeLayout)convertView.findViewById(R.id.user_item_relative);
                holder.badgeView = new BadgeView(mContext, holder.user_item_relative);
                holder.unreadmsgnumber = (TextView)convertView.findViewById(R.id.unreadmsgnumber);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			ContactGroup detail=mList.get(position);
//            holder.mTitle.setText(detail.getTitle());
//            holder.mContent.setText(detail.getContent());
//            holder.mGentie.setText(detail.getGentiecount()+"跟帖");
			int cgrouptype = detail.getType();////0 contact,1 group
			switch(cgrouptype){
				case 0:
					if(detail.getName()!=null
							&& !detail.getName().equalsIgnoreCase("null")
							&& detail.getName().length()!=0)
						holder.contentView.setText(detail.getName());
					else
						holder.contentView.setText(detail.getUsername());
					holder.imageView.set_url(detail.getAvatarPath());
					holder.user_item_htv_account.setText(detail.getUsername());
		            holder.user_item_htv_sign.setText(detail.getNote());
		            
	            	if(detail.getSex()==1){//0 默认未知，1男，2女
	            		holder.user_item_layout_gender.setBackgroundResource(R.drawable.bg_gender_male);
	            		holder.user_item_iv_gender.setImageResource(R.drawable.ic_user_male);
	            	}else{
	            		holder.user_item_layout_gender.setBackgroundResource(R.drawable.bg_gender_famal);
	            		holder.user_item_iv_gender.setImageResource(R.drawable.ic_user_famale);
	            	}
	            	holder.user_item_iv_icon_group_role.setVisibility(View.GONE);
	            	int age = 0;
	                if(detail.getBirthyear()!=null
	                		&& !detail.getBirthyear().equalsIgnoreCase("null")
	                		&& detail.getBirthyear().length()!=0
	                		&& detail.getBirthmonth()!=null
	                		&& !detail.getBirthmonth().equalsIgnoreCase("null")
	                		&& detail.getBirthmonth().length()!=0
	                		&& detail.getBirthday()!=null
	                		&& !detail.getBirthday().equalsIgnoreCase("null")
	                		&& detail.getBirthday().length()!=0){
	                	
	                	try{
	                		age = TextUtils.getAge(Integer.parseInt(detail.getBirthyear()),
	                				Integer.parseInt(detail.getBirthmonth()),
	                				Integer.parseInt(detail.getBirthday()));
	                	}catch(Exception e){
	                		e.printStackTrace();
	                		age = 0;
	                	}
	                }
	                if(age>200)
	                	holder.user_item_htv_age.setText("未知");
	                else
	                	holder.user_item_htv_age.setText(age+"");
					break;
				case 1:
					if(detail.getTagname()!=null
							&& !detail.getTagname().equalsIgnoreCase("null")
							&& detail.getTagname().length()!=0)
						holder.contentView.setText(detail.getTagname());
					else
						holder.contentView.setText(detail.getTagid());
					holder.imageView.set_url(detail.getPic());
					holder.user_item_htv_account.setText(detail.getTagid());
					if(detail.getSubject()!=null
							&& !detail.getSubject().equalsIgnoreCase("null")
							&& detail.getSubject().length()!=0)
						holder.user_item_htv_sign.setText(detail.getSubject());
					else
						holder.user_item_htv_sign.setText("");
		            holder.user_item_layout_gender.setBackgroundResource(R.drawable.bg_grouplist_ower);
	        		holder.user_item_iv_gender.setImageResource(R.drawable.ic_userinfo_group4);
	        		holder.user_item_iv_icon_group_role.setVisibility(View.VISIBLE);
	        		holder.user_item_htv_age.setText("群组");
	        		mImageFetcher.loadImage(detail.getPic().replace("localhost", "10.0.2.2"), holder.imageView);
					break;
				default:
					break;
			}
//			holder.contentView.setText(detail.getName()+detail.getTagname()+detail.getTagid()+detail.getUid());
            
            //设置图片
          /*  try{
            	File file=new File(Environment.getExternalStorageDirectory()+"/chinanews",detail.getTitle());
            	if(file.exists()&&file.length()>0){
            		holder.mImage.setImageURI(Uri.fromFile(file));
            	}else{
            		//去下载
            		Bitmap bitmap=HttpConnect.getImage(detail.getPicpath(), detail.getTitle());
            		holder.mImage.setImageBitmap(bitmap);
            	}
            }catch(Exception e){
            	
            }*/
//			mImageFetcher.loadImage(detail.getPic(), holder.imageView);
			return convertView;
		}
		
        /**
        249	     * 当列表单元滚动到可是区域外时清除掉已记录的图片视图
        250	     *
        251	     * @param view
        252	     */
        @Override
        public void onMovedToScrapHeap(View view) {
//        	if(flagType){
	            ViewHolder holder = (ViewHolder) view.getTag();
	//        	this.imageViews.remove(holder.avatar);
	//        	this.imageViews.remove(holder.picPhoto);
	            if(holder!=null && holder.imageView!=null){
		            holder.imageView.recycle();
		            holder.imageView = null;
	            }
//        	}
        }
	}
	private static class ViewHolder {
		private FlowView imageView;
//		private TextView mTitle;
//		private TextView mContent;
//		private TextView mGentie;
		private HandyTextView contentView;
        TextView timeView;
        
        LinearLayout user_item_layout_gender;//20140731 added
        ImageView user_item_iv_gender;
        HandyTextView user_item_htv_age;
        
        HandyTextView user_item_htv_account;//帐号
        HandyTextView user_item_htv_sign;//个性签名
        
        ImageView user_item_iv_icon_group_role;
        
        RelativeLayout user_item_relative;
        
        BadgeView badgeView;
        TextView unreadmsgnumber;
	}
	
	////////////////////////刷新部分数据//////////////////////////////////////
	private void initRefreshView(LinkedList<ContactGroup> mList){
		mAdapter = new CustomListAdapter(this, mList);
		mListView = (CustomListView)this.findViewById(R.id.mListView);
		mListView.setAdapter(mAdapter);
//		mListView.setOnClickListener();//
		mListView.setOnItemClickListener(mOnContactClick);//
		
//		CustomListAdapter adapter=maps.get(item);
//		CustomListView listView=mapList.get(item);
//		if(adapter==null){
//			maps.put(item, mAdapter);
//		}
//		if(listView==null){
//			mapList.put(item, mListView);
//		}

		mListView.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				getContactList(ConstantValues.refresh);
//				getContactList();
			}
		});

		mListView.setOnLoadListener(new OnLoadMoreListener() {
			@Override
			public void onLoadMore() {
				getContactList(ConstantValues.load);
//				getContactList();
			}
		});
		
	}
	
	
	
	private Handler mHandler = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				//没有获取到数据：可能网络问题
				Toast.makeText(mContext, "没有获取到数据：可能网络问题", Toast.LENGTH_SHORT).show();
				break;
			case REFRESH_DATA_FINISH:
				if(mAdapter!=null){
					List<ContactGroup> newNews=(List<ContactGroup>) msg.obj;
					for(ContactGroup news :newNews){
						mAdapter.mList.addFirst(news);
					}
					mAdapter.notifyDataSetChanged();
				}
				mListView.onRefreshComplete();	//下拉刷新完成
				break;
			case LOAD_DATA_FINISH:
				if(mAdapter!=null){
					mAdapter.mList.addAll((LinkedList<ContactGroup>)msg.obj);
					mAdapter.notifyDataSetChanged();
				}
				mListView.onLoadMoreComplete();	//加载更多完成
				break;
//			case PIC:
//				mViewPager.setCurrentItem(currentPosition);
//				break;
			default:
				break;
			}
		};
	};
	
	public void parserData(final int type) {
		// 去服务器去数据
//		refreshData(type);
		
		switch (type) {
//		case 0:
//			initRefreshView(linkedList);
//			break;
		case 0:
			Message load0 = mHandler.obtainMessage(LOAD_DATA_FINISH, linkedList);
			mHandler.sendMessage(load0);
			break;
		case 1:
			Message refresh = mHandler.obtainMessage(REFRESH_DATA_FINISH,
					linkedList);
			mHandler.sendMessage(refresh);
			break;
		case 2:
			Message load = mHandler.obtainMessage(LOAD_DATA_FINISH, linkedList);
			mHandler.sendMessage(load);
			break;

		default:
			break;
		}
	}
	
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
			getContactList(ConstantValues.refresh);
		}
	}
	private class OnMiddleImageButtonClickListener implements
	onMiddleImageButtonClickListener {

		@Override
		public void onClick() {
			flag = true;
			getContactList(ConstantValues.refresh);
		}
	}
	private boolean isWork = false;
	public class OnSwitcherButtonClickListener implements
	onSwitcherButtonClickListener {
	
		@Override
		public void onClick(SwitcherButtonState state) {
			if(!isWork){//20141120防止恶意切换
//				FragmentTransaction ft = getSupportFragmentManager()
//						.beginTransaction();
//				ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
				switch (state) {
				case LEFT:
					
					mHeaderLayout.setDefaultTitle("好友列表",null);
//					ft.replace(R.id.contactframe_layout_content, contactListsFragment).commit();
					break;
			
				case RIGHT:
					mHeaderLayout.setDefaultTitle("招呼盒子",null);
//					ft.replace(R.id.contactframe_layout_content, greetInfosFragment).commit();
					break;
				}
			}
		}

	}
	
	
    /**
     * Event simple click on item of the contact list.
     * 单击某联系人，打开chat聊天对话框
     */
//    private class BeemContactListOnClick implements PLA_ListView.OnItemClickListener {
    public class ContactGroupListOnClick implements OnItemClickListener {//private
		/**
		 * Constructor.
		 */
		public ContactGroupListOnClick( ) {
		}
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int pos, long lpos) {
////			ptrlv.getAdapter().getView(pos, v, ptrlv);  
//			ptrlv.getRefreshableView().getAdapter().getView(pos, v, ptrlv); 
//			RelativeLayout user_item_relative = (RelativeLayout)v.findViewById(R.id.user_item_relative);
//			BadgeView badgeView = new BadgeView(mContext, user_item_relative);
//            badgeView.setText("2");
//            badgeView.show();
////            holder.badgeView.hide();
            
			ViewHolder holder = (ViewHolder) v.getTag();
			if(holder.badgeView.isShown())
				holder.badgeView.hide();
//			holder.unreadmsgnumber.setVisibility(View.GONE);
			
			
		    ContactGroup c = (ContactGroup)linkedList.get(pos-1);//pos-1
		    
		    Toast.makeText(MainActivity.this, "单击：" + (pos-1), Toast.LENGTH_SHORT).show();
		    
////		    UnReadMsgNumber unReadMsgNumber = new UnReadMsgNumber();
////		    unReadMsgNumber.setKey(StringUtils.parseName(c.getJID()));
////		    unReadMsgNumber.setUnreadnumber(0);
////		    duitangInfoAdapter.addUnReadMsgNumber(unReadMsgNumber);
//		    UnReadMsgNumberMap.put(StringUtils.parseName(c.getJID()), ""+0);
//		    
//		    
		    Intent i = new Intent(MainActivity.this,ChatActivity.class);
//		    i.setData(c.getUuid());
//            if(c.getAvatarId()!=null 
//            		&& c.getAvatarId().length()!=0 
//            		&& !c.getAvatarId().equalsIgnoreCase("null")
//            		&& (
//            				c.getAvatarId().toLowerCase().endsWith(".jpg")
//            				|| c.getAvatarId().toLowerCase().endsWith(".png")
//            				|| c.getAvatarId().toLowerCase().endsWith(".bmp")
//            				|| c.getAvatarId().toLowerCase().endsWith(".gif")
//            			)
//            		&& c.getJIDWithRes().indexOf("@conference.")==-1)
//            	i.putExtra("headimg", XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(c.getJIDWithRes())+"/"+c.getAvatarId());//+"thumbnail_"
//		    i.putExtra("myheadimg", myheadimg);
//		    i.putExtra("username",c.getName());
//		    i.putExtra("myusername",myusername);
		    i.putExtra("uid", c.getUid());
		    i.putExtra("uuid", c.getUuid());
		    i.putExtra("username", c.getUsername());
		    i.putExtra("name", c.getName());
		    i.putExtra("avatarpath", c.getAvatarPath());
		    
		    i.putExtra("tagid", c.getTagid());
		    i.putExtra("tagname", c.getTagname());
		    i.putExtra("pic", c.getPic());
            startActivity(i);
		}
    }
}
